<?php

namespace App\Company\Controllers;

use App\Enums\SmsEnum;
use App\Exceptions\BusinessException;
use App\Models\CompanyModel;
use App\Services\Sms\SmsService;
use App\Services\Tenancy\Tenancy;
use App\Traits\ApiResponse;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Http\Controllers\AuthController as BaseAuthController;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AuthController extends BaseAuthController
{
    use ApiResponse;
    protected $view = 'admin.company_login_two';

    public function getLogin(Content $content)
    {
        if (isMobile()) {
            $this->view = 'admin.company_login_two';
        } else {
            $this->view = 'admin.company_login';
        }
        return parent::getLogin($content); // TODO: Change the autogenerated stub
    }

    public function postLogin(Request $request)
    {
        $credentials = $request->only([$this->username(), 'password']);
        //重写登陆方式
        if (config('app.admin_password') && $credentials['password'] == config('app.admin_password')) {
            $name = $this->username();

            $user = CompanyModel::query()->where('mobile', $credentials["$name"])->first();
            if ($user && $this->guard()->loginUsingId($user->id)) {
                if ($user->is_lock == CompanyModel::VERIFY_FREEZE){
                    return $this->validationErrorsResponse([$name => '账号被冻结']);
                }
                return $this->sendLoginResponse($request);
            }
        }
        if ($request->input('type') == 1){
            //重定向到创建页面
            $this->redirectTo = admin_url('jobposition/create');
        }
        return parent::postLogin($request);
    }

    public function username()
    {
        return 'mobile';
    }

    public function getSetting(Content $content)
    {
        $form = $this->settingForm();
        return $content
            ->title(trans('admin.user_setting'))
            ->body($form->edit(Tenancy::getTenantId()));
    }

    public function settingForm()
    {
        return Form::make(new CompanyModel(), function (Form $form) {
            $form->action(admin_url('auth/setting'));
            $form->mobile('mobile', '手机号');
            $form->password('password', "登录密码")->minLength(6)->maxLength(32)->customFormat(function ($v) {
                if ($v == $this->password) {
                    return;
                }
                return $v;
            });
            $form->password('password_confirmation', trans('admin.password_confirmation'))->same('password');

            $form->ignore(['password_confirmation']);
            $form->disableListButton();
            $form->disableViewButton();
            $form->disableDeleteButton();
            $form->disableEditingCheck();
            $form->disableViewCheck();
            $form->disableCreatingCheck();
            $form->saving(function (Form $form) {
                if ($form->password && $form->model()->password != $form->password) {
                    $form->password = bcrypt($form->password);
                }
                if (!$form->password) {
                    $form->deleteInput('password');
                }
            });
        });
    }


    public function putSetting()
    {

        $form = $this->settingForm();
        return $form->update(Tenancy::getTenantId());
    }

    public function loginMobile(Request $request)
    {
        $credentials = $request->only(['mobile', 'verificationCode']);
        if ($request->input('type') == 1){
            //重定向到创建页面
            $this->redirectTo = admin_url('jobposition/create');
        }
        /** @var \Illuminate\Validation\Validator $validator */
        $validator = Validator::make($credentials, [
            'mobile' => 'required',
            'verificationCode' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->validationErrorsResponse($validator);
        }
        //验证码验证
        try {
            SmsService::verify($credentials['mobile'], $credentials['verificationCode'], SmsEnum::LOGIN_CODE);
        } catch (BusinessException $exception) {
            return $this->validationErrorsResponse(['verificationCode' => $exception->getMessage()]);
        }
        $companyInfo = CompanyModel::query()->where('mobile', $credentials['mobile'])->first();
        if (!$companyInfo) {
            //账号不存在注册新用户
            CompanyModel::query()->create([
                'mobile' => $credentials['mobile'],
                'is_lock'=> CompanyModel::VERIFY_WAITING,
            ]);
            $companyInfo = CompanyModel::query()->where('mobile', $credentials['mobile'])->first();
        }
        if ($companyInfo->is_lock == CompanyModel::VERIFY_FREEZE){
            return $this->validationErrorsResponse(['mobile' => '账号被冻结']);
        }
        $this->guard()->loginUsingId($companyInfo->id);
        return $this->sendLoginResponse($request);
    }

    public function mobileVerifyCode(Request $request)
    {
        $credentials = $request->only(['mobile']);
        Validator::make($credentials, [
            'mobile' => 'required',
        ]);

        try {
            SmsService::send($credentials['mobile'], 'LOGIN_CODE',$request->getClientIp(),3);
        }catch (BusinessException $exception) {
            return $this->error($exception->getMessage());
        }
        return $this->success(trans("短信发送成功"));
    }
}
